'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 穿装备
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../../consts/code');
var equipConf = require('../../../../config/equipConf');
var taskService = require('../../../../services/taskService');
var PlayerManager = require('../../../../libs/playerManager');
var roleService = require('../../../../services/roleService.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var equip_id = msg.equip_id;

    if (!equip_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['bag', 'role', 'skill', 'build', 'accrued'], cb);
            },
            function (cb) {
                var role_model = player_manager.role;
                var bag_model = player_manager.bag;

                if (!!bag_model.isEquip(equip_id)) {
                    return next(null, {
                        code: Code.BAG_EQUIP_HAVE_WEAR
                    });
                }

                // 判断物品是否存在
                var equip = bag_model.getEquip(equip_id);
                if (!equip) {
                    return next(null, {
                        code: Code.BAG_ITEM_NOT_EXIST
                    });
                }

                // 是否职业是否符合
                var equip_type = equip.getType();
                var equip_type_conf = equipConf.getEquipTypeConf(equip_type);

                // 判断职业是否符合
                if (equip_type_conf.profession !== 0 &&
                    equip_type_conf.profession != role_model.getJob()) {
                    return next(null, {
                        code: Code.BAG_EQUIP_JOB_NOT_MATCH
                    });
                }

                // 穿上装备
                if (!bag_model.equip(equip_id)) {
                    return next(null, {
                        code: Code.EQUIP_ITEM_FAIL
                    });
                }

                // 刷新战力
                roleService.updateHeroPower(player_manager);

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
